package com.qianfeng.xinyihezi.xinyihezi.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.qianfeng.xinyihezi.xinyihezi.R;
import com.qianfeng.xinyihezi.xinyihezi.activity.GoodsScreenActivity;
import com.qianfeng.xinyihezi.xinyihezi.adapter.ClassiftLeftAdapter;
import com.qianfeng.xinyihezi.xinyihezi.adapter.RecyclerViewDetailClassiftAdapter;
import com.qianfeng.xinyihezi.xinyihezi.adapter.RecyclerViewWholeAdapter;
import com.qianfeng.xinyihezi.xinyihezi.config.NetConfig;
import com.qianfeng.xinyihezi.xinyihezi.config.RetrofitInterface;
import com.qianfeng.xinyihezi.xinyihezi.jsondecode.DecodeDetailClassift;
import com.qianfeng.xinyihezi.xinyihezi.jsondecode.DecodeLeftClassift;
import com.qianfeng.xinyihezi.xinyihezi.model.DetailData;
import com.qianfeng.xinyihezi.xinyihezi.model.LeftData;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Tcoy on 2016/11/13.
 */

public class ClassiftModelFragment extends Fragment implements View.OnClickListener {
    private String TAG = getClass().getSimpleName();
    private Retrofit mRetrofit;
    private RetrofitInterface mRetrofitInterface;
    private DecodeLeftClassift mDecodeLeftClassift;
    private LeftData mLeftData;
    private ListView mListViewLeftClassift;
    private ClassiftLeftAdapter classiftLeftAdapter;

    private RecyclerView mRecyclerViewWhole;
    private DecodeDetailClassift mDecodeDetailClassift;
    private List<DetailData> mDetailDataList;
    private RecyclerViewWholeAdapter recyclerViewWholeAdapter;
    private int currPosition = 1;
    private RecyclerViewHeader mRecyclerViewHeader;
    private ImageView imgHeadPng;

    public static Handler handler;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.classift_model_layout, null);
        initView(view);
        initRetrofit();
        initData();
        loadData();
        setListener();
        return view;
    }

    /**
     * 设置监听事件
     */
    private void setListener() {
        //左侧的大分类
        mListViewLeftClassift.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                classiftLeftAdapter.setCurrItemPosition(position);
                classiftLeftAdapter.notifyDataSetChanged();
                loadDetailClassiftData(position);
            }
        });
        //右边的小分类
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.i(TAG, "handleMessage: " + msg.arg1);
                loadSmallData(msg.arg1);
            }
        };
    }

    /**
     * 加载小分类的 数据
     */
    private void loadSmallData(int arg1) {
        toastShow(arg1 + "");
        Intent intent = new Intent(getActivity(), GoodsScreenActivity.class);
        intent.putExtra("category", arg1);
        startActivity(intent);
    }

    /**
     * 加载详细分类的数据
     *
     * @param position
     */
    private void loadDetailClassiftData(final int position) {
        mRetrofitInterface.getDetailJson(mLeftData.getClassiftLeftDataList().get(position).getCat_id()).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String resultJson = response.body().string();
                        List<DetailData> detailDatas = mDecodeDetailClassift.decodeDetailClassift(resultJson);
                        mDetailDataList.clear();
                        mDetailDataList.addAll(detailDatas);
                        recyclerViewWholeAdapter.notifyDataSetChanged();
                        currPosition = position;
                        Picasso.with(getActivity()).load(mLeftData.getClassiftLeftDataList().get(position).getImage_url()).into(imgHeadPng);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        mRetrofitInterface.getLeftClassiftJson().enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String resultJson = response.body().string();
                        LeftData leftDataNotifcation = mDecodeLeftClassift.startDecode(resultJson);
                        mLeftData.setClassiftLeftDataList(leftDataNotifcation.getClassiftLeftDataList());
                        mLeftData.setClassiftLeftBannerList(leftDataNotifcation.getClassiftLeftBannerList());
                        classiftLeftAdapter.notifyDataSetChanged();
                        Picasso.with(getActivity()).load(mLeftData.getClassiftLeftDataList().get(0).getImage_url()).into(imgHeadPng);
                        loadDetailClassiftData(0);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                toastShow("网络错误" + t.getMessage());
            }
        });
    }

    /**
     * 初始化Retrofit
     */
    private void initRetrofit() {
        mRetrofit = new Retrofit.Builder().baseUrl(NetConfig.BASE_LEFTCLASSIFT).build();
        mRetrofitInterface = mRetrofit.create(RetrofitInterface.class);
    }

    /**
     * 初始化View
     */
    private void initView(View view) {
        mListViewLeftClassift = (ListView) view.findViewById(R.id.listViewLeftClassift);
        mRecyclerViewWhole = (RecyclerView) view.findViewById(R.id.recyclerViewClassift);//整体中的这个RecyclerView线性的
        mRecyclerViewHeader = (RecyclerViewHeader) view.findViewById(R.id.recyclerViewHead);
        imgHeadPng = (ImageView) view.findViewById(R.id.imageRecyclerViewHead);
        imgHeadPng.setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mDetailDataList = new ArrayList<>();
        mDecodeDetailClassift = new DecodeDetailClassift();
        mLeftData = new LeftData();
        mDecodeLeftClassift = new DecodeLeftClassift();
        classiftLeftAdapter = new ClassiftLeftAdapter(getActivity(), mLeftData);
        mListViewLeftClassift.setAdapter(classiftLeftAdapter);

        RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        mRecyclerViewWhole.setLayoutManager(linearLayoutManager);
        mRecyclerViewHeader.attachTo(mRecyclerViewWhole, true);
        recyclerViewWholeAdapter = new RecyclerViewWholeAdapter(mDetailDataList, getActivity());
        mRecyclerViewWhole.setAdapter(recyclerViewWholeAdapter);
    }

    /**
     * 测试用Toast
     */
    private void toastShow(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageRecyclerViewHead:
                toastShow(mLeftData.getClassiftLeftBannerList().get(currPosition).getTable_id());
                break;
        }
    }
}
